
namespace EasyThreadingGame
{
    using System;
    using System.Threading;
    using EasyThreading;
    using Microsoft.Xna.Framework;
    using Microsoft.Xna.Framework.Graphics;
    using Microsoft.Xna.Framework.Input;

    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        TaskCallback task;

        // used to hang on to input state
        ButtonState lastAButtonState = ButtonState.Released;
        bool spaceIsDown = false;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            //////////////////////////////////////////////////////////
            // create the TaskExecutor service
            TaskExecutor executor = new TaskExecutor(3);
            this.Services.AddService(typeof(ITaskExecutor), executor);
            this.task = this.LongRunningAction;
            //////////////////////////////////////////////////////////

            this.Components.Add(new FrameRateCounter(this));

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // get gamepad state for XBox
            if (GamePad.GetState(PlayerIndex.One).Buttons.A == ButtonState.Pressed &&
                this.lastAButtonState != ButtonState.Pressed)
            {
                this.DoTask();
            }

            this.lastAButtonState = GamePad.GetState(PlayerIndex.One).Buttons.A;

            // get keyboard state for windows
            if (Keyboard.GetState().IsKeyDown(Keys.Space) &&
                !this.spaceIsDown)
            {
                this.DoTask();
                this.spaceIsDown = true;
            }
    
            // reset the key down state
            if (!Keyboard.GetState().IsKeyDown(Keys.Space))
            {
                this.spaceIsDown = false;
            }

            base.Update(gameTime);
        }

        /// <summary>
        /// Uses the task executor to perform a task
        /// </summary>
        private void DoTask()
        {
            //////////////////////////////////////////////////////////
            // this is the important bit
            ITaskExecutor te = (ITaskExecutor)this.Services.GetService(typeof(ITaskExecutor));
            te.QueueTask(this.task, null);
            //////////////////////////////////////////////////////////
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here

            base.Draw(gameTime);
        }

        protected override void Dispose(bool disposing)
        {
            //////////////////////////////////////////////////////////
            // clean up
            ITaskExecutor te = (ITaskExecutor)this.Services.GetService(typeof(ITaskExecutor));
            IDisposable disp = te as IDisposable;
            disp.Dispose();
            //////////////////////////////////////////////////////////

            base.Dispose(disposing);
        }

        /// <summary>
        /// Performs a long running action.
        /// </summary>
        /// <param name="param">Optional paramter.</param>
        private void LongRunningAction(object param)
        {
            Thread.Sleep(5000);
        }
    }
}
